package com.muse.designpatterns.prototype;

import java.util.ArrayList;
import java.util.List;

/**
 * 浅拷贝与深拷贝
 */
public class Prototype1 implements Cloneable{
    private String name;
    private List<String> arrayList = new ArrayList<>();

    public void setName(String name) {
        this.name = name;
    }

    public void setValue(String value) {
        this.arrayList.add(value);
    }

    public List<String> getValue() {
        return arrayList;
    }
    public void setArrayList(List<String> arrayList) {
        this.arrayList = arrayList;
    }

    public List<String> getArrayList() {
        return arrayList;
    }

    public static void main(String[] args) {
        Prototype1 prototype1 = new Prototype1();
        prototype1.setName("Original object");
        prototype1.setValue("Original object");

        Prototype1 clonePrototype = prototype1.clone();
        clonePrototype.setName("clone object");
        clonePrototype.setValue("clone object");
        /**
         * 发现执行了clone对象的setValue（）方法后，也修改了prototype1中arrayList的值
         */
        System.out.println("prototype1"+prototype1);
        System.out.println("clonePrototype"+clonePrototype);
    }



    /**
     * 浅拷贝
     * @return
     */
    @Override
//    public Prototype1 clone() {
//        try {
//            Prototype1 clone = (Prototype1) super.clone();
//            // TODO: copy mutable state here, so the clone can't change the internals of the original
//            return clone;
//        } catch (CloneNotSupportedException e) {
//            throw new AssertionError();
//        }
//    }

    /**
     * 深拷贝
     * @return
     */
    public Prototype1 clone(){
        Prototype1 prototype1 = null;
        try {
            prototype1 = (Prototype1) super.clone();
            prototype1.setArrayList(new ArrayList<>(prototype1.getArrayList()));
            // TODO: copy mutable state here, so the clone can't change the internals of the original
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
        return prototype1;
    }

}
